//
//  NSErrorExtensions.swift
//  Entrance
//
//  Created by chunhuiLai on 2018/1/15.
//  Copyright © 2018年 chunhuiLai. All rights reserved.
//

import Foundation
import SwiftyJSON
import Moya

protocol JSONAbleType {
    static func fromJSON(_: JSONDictionary) -> Self
}

final class GenericError: NSObject, JSONAbleType {
    let detail: JSONDictionary
    let message: String
    let type: String
    
    init(type: String, message: String, detail: JSONDictionary) {
        self.detail = detail
        self.message = message
        self.type = type
    }
    
    static func fromJSON(_ json: JSONDictionary) -> GenericError {
        let json = JSON(json)
        
        let type = json["type"].stringValue
        let message = json["message"].stringValue
        var detailDictionary = json["detail"].object as? JSONDictionary
        
        detailDictionary = detailDictionary ?? [:]
        return GenericError(type: type, message: message, detail: detailDictionary!)
    }
}

extension NSError {
    
    func artsyServerError() -> String {
        if let errorJSON = userInfo["data"] as? JSONDictionary {
            let error =  GenericError.fromJSON(errorJSON)
            return "\(error.message) - \(error.detail) + \(error.detail)"
            
        } else if let response = userInfo["data"] as? Response {
            let stringData = String(data: response.data, encoding: String.Encoding.utf8)
            return "Status Code: \(response.statusCode), Data Length: \(response.data.count), String Data: \(String(describing: stringData))"
        }
        
        return "\(userInfo)"
    }
}
